package cn.bas;


import cn.bas.controller.UserController01;
import cn.bas.service.UserService;
import cn.bas.vo.UserVo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

@RunWith(SpringRunner.class)
@WebMvcTest(UserController01.class) //指定相应的类进行测试，该注解包含@AutoConfigureMockMvc
public class UserControllerTest02 {

    @Autowired
    private MockMvc mvc;

    @MockBean // 引入userService
    private UserService userService;

    @Test
    public void testGet2() throws Exception {
        // Mock UserService 的 get 方法
        System.out.println("before mock:" + userService.get(1));
        // Mockito 创建的 UserService Mock 代理对象
        Mockito.when(userService.get(1)).thenReturn(
                new UserVo().setId(1).setUsername("tom")); // 通过 Mockito 进行 Mock userService 的 #get(Integer id) 方法，
                                                            // 当传入的 id = 1 方法参数时，返回 UserVO 对象。
        System.out.println("after mock:" + userService.get(1)); // <1.3>

        // 查询用户列表
        ResultActions resultActions = mvc.perform(MockMvcRequestBuilders.get("/users/v2/1"));
        // 校验结果
        resultActions.andExpect(MockMvcResultMatchers.status().isOk()); // 响应状态码 200
        resultActions.andExpect(MockMvcResultMatchers.content().json("{\n" +
                "    \"id\": 1,\n" +
                "    \"username\": \"tom\"\n" +
                "}")); // 响应结果
    }
}
